# ##### BEGIN GPL LICENSE BLOCK #####
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####

# <pep8 compliant>

import sys

from Mathutils import Vector
from Mathutils import Matrix
from Mathutils import Euler

from os.path import exists
from os.path import join


class B2XP_Vertex:
    """ Defines an x-plane vertex

    Converts a blender vector, euler or ... using its translation matrix
    into an x-plane coordinate system vertex
    

    """

    LIMIT = 0.0001    # max distance between vertices for them to be merged
    ROUND = 4         # Precision

    def __init__ (self):
        self.faces = []   # indices into face array
        self.x = 0.0
        self.y = 0.0
        self.z = 0.0

    @staticmethod
    def from_vector(vector, matrix):
        """ Constructor given a vector and translation matrix

        Keyword arguments:
        vector -- A blender Vector object
        matrix -- A blender translation 4x4 matrix

        """
        if not isinstance(vector, Vector) or not isinstance(matrix, Matrix):
            raise TypeError

        vertex = B2XP_Vertex()
        vertex.apply_and_scale(vector.x, vector.y, vector.z, matrix)
        return vertex

    @staticmethod
    def from_euler(euler, matrix):
        """ Constructor given a euler and translation matrix

        Keyword arguments:
        euler.x -- heading in radians.
        euler.y -- pitch in radians.
        euler.z -- roll in radians.
        matrix -- A blender translation 4x4 matrix

        """
        if not isinstance(euler, Euler) or not isinstance(matrix, Matrix):
            raise TypeError

        vertex = B2XP_Vertex()
        vertex.apply_and_scale(euler.x, euler.y, euler.z, matrix)
        return vertex

    def apply_and_scale(self, x, y, z, mm):
        """ apply scale, translate and swap y and z axes

        """
        self.x = round((mm[0][0] * x) + (mm[1][0] * y) + 
            (mm[2][0] * z) + mm[3][0], B2XP_Vertex.ROUND)

        self.y = round((mm[0][2] * x) + (mm[1][2] * y) + 
            (mm[2][2] * z) + mm[3][2], B2XP_Vertex.ROUND)

        self.z = -round((mm[0][1] * x) + (mm[1][1] * y) +
            (mm[2][1] * z) + mm[3][1], B2XP_Vertex.ROUND)


class B2XP_DataRef:
    """ X-Plane DataRefs.txt file reader and storage class

    """
    DATA_REF_FILENAME = "DataRefs.txt"
    data_refs = {}
    heirarchy = {}

    def __init__ (self, script_paths):
        """

        """
        for path in script_paths:
            fname = join(path, self.DATA_REF_FILENAME)
            print(fname)

            if exists(fname):
                fh = open(fname, 'rU')
                dd = fh.readline().split()
                if len(dd) != 7 or dd[0] != '2': 
                    raise IOError(0, "Error Reading DataRefs.txt file. Invalid Header.")

                for line in fh:
                    dd = line.split()
                    if not dd: 
                        continue
                    if len(dd) < 3: 
                        raise IOError(0, "Error Reading DataRefs.txt file. Len < 3.")
                    ref = dd[0].split('/')
                    print(ref)
        
        #raise IOError(0, "Missing DataRefs.txt file. Please re-install.")    
    

if __name__ == "__main__":
    pass